<?php

namespace app\common\library;

/**
 * 火山云对象存储(TOS)简化版实现
 */
class VolcengineTos
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $region;
    protected $bucket;
    protected $endpoint;

    public function __construct($config = [])
    {
        $this->accessKeyId = $config['access_key_id'] ?? '';
        $this->accessKeySecret = $config['access_key_secret'] ?? '';
        $this->region = $config['region'] ?? 'cn-beijing';
        $this->bucket = $config['bucket'] ?? '';
        $this->endpoint = $config['endpoint'] ?? "tos-{$this->region}.volces.com";
    }

    /**
     * 上传文件
     *
     * @param string $filePath 本地文件路径
     * @param string $objectKey 对象键（在TOS中的文件路径）
     * @return array|false
     */
    public function uploadFile($filePath, $objectKey)
    {
        if (!file_exists($filePath)) {
            return false;
        }

        // 读取文件内容
        $fileContent = file_get_contents($filePath);
        if ($fileContent === false) {
            return false;
        }

        // 构造上传URL
        $url = "https://{$this->endpoint}/{$objectKey}";

        // 构造请求头
        $headers = [
            'Authorization: FACD admin:' . $this->accessKeyId . ':' . $this->generateSignature($objectKey, $fileContent),
            'Content-Type: application/octet-stream',
            'Date: ' . gmdate('D, d M Y H:i:s T')
        ];

        // 发起PUT请求上传文件
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, true);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 200 && $httpCode < 300) {
            // 上传成功，返回文件URL
            return [
                'url' => "https://{$this->bucket}.{$this->endpoint}/{$objectKey}",
                'object_key' => $objectKey
            ];
        }

        return false;
    }

    /**
     * 简化的签名生成方法（实际使用中需要根据火山云文档实现完整签名）
     *
     * @param string $objectKey
     * @param string $content
     * @return string
     */
    protected function generateSignature($objectKey, $content)
    {
        // 这里只是一个示例实现，实际应用中需要根据火山云的签名算法实现
        // 参考：https://www.volcengine.com/docs/6349/155154
        $stringToSign = "PUT\n\napplication/octet-stream\n" . gmdate('D, d M Y H:i:s T') . "\n/{$this->bucket}/{$objectKey}";
        return base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret, true));
    }

    /**
     * 生成预签名URL（用于下载）
     *
     * @param string $objectKey
     * @param int $expires 过期时间（秒）
     * @return string
     */
    public function generatePresignedUrl($objectKey, $expires = 3600)
    {
        $expireTime = time() + $expires;
        $signKey = hash_hmac('sha1', $this->accessKeySecret, $expireTime, true);
        $stringToSign = "GET\n\n\n{$expireTime}\n/{$this->bucket}/{$objectKey}";
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $signKey, true));

        return "https://{$this->bucket}.{$this->endpoint}/{$objectKey}?Expires={$expireTime}&AccessKeyId={$this->accessKeyId}&Signature=" . urlencode($signature);
    }
}
